package cn.tanglong.org.controller;

import cn.tanglong.basic.util.AjaxResult;
import cn.tanglong.basic.util.PageList;
import cn.tanglong.org.domain.Sdt;
import cn.tanglong.org.domain.Sdt;
import cn.tanglong.org.query.SdtQuery;
import cn.tanglong.org.service.ISdtService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sdt")
@Api(tags = "数据字典类型表", description = "主要种类")
public class SdtController {

    @Autowired
    private ISdtService sdtService;

    @GetMapping("{id}")
    @ApiOperation(value = "查询类型",notes = "根据id查询")
    public Sdt findOne(@PathVariable("id") Long id){
        return sdtService.loadById(id);
    }

    @GetMapping
    @ApiOperation(value = "查询所有类型",notes = "查询所有信息")
    public List<Sdt> findAll(){
        return sdtService.loadAll();
    }

    // 分页查询
    // RequestBody 把请求体中的数据调整成json格式，封装到query中
    @PostMapping
    @ApiOperation(value = "查询分页",notes = "需要当前页和每页数据")
    public PageList<Sdt> queryPage(@RequestBody SdtQuery query){
        return sdtService.queryList(query);
    }

    @DeleteMapping("{id}")
    @ApiOperation(value = "删除类型",notes = "根据id删除")
    public AjaxResult deleteById(@PathVariable("id") Long id){
        try {
            sdtService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            // 链式编程  装杯常用
            return AjaxResult.me().setMsg("操作失败");
        }
    }

    @PatchMapping
    @ApiOperation(value = "批量删除",notes = "根据id数组删除")
    public AjaxResult patchDelete(@RequestBody List<Long> ids){
        try {
            sdtService.patchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            // 链式编程  装杯常用
            return AjaxResult.me().setMsg("操作失败");
        }
    }

    @PutMapping()
    @ApiOperation(value = "类型添加或修改",notes = "如果有id就是修改，没id就是添加")
    public AjaxResult addOrUpdateById(@RequestBody Sdt sdt){
        try {
            if (sdt.getId() == null) {
                sdtService.add(sdt);
            } else {
                sdtService.update(sdt);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            // 链式编程  装杯常用
            return AjaxResult.me().setMsg("操作失败");
        }
    }
}
